﻿using Newtonsoft.Json;

using NPOI.SS.Formula.Functions;

using PLCS.Shared.Common.Constant;

using RestSharp;

namespace PLCS.Client.Service.Client;

/// <summary>
/// http请求类
/// </summary>
public class HttpRestClient
{
    public async Task<ApiResponse> ExecuteAsync(RequestParam requestParam)
    {
        var options = new RestClientOptions(AddressManager.ApiAddress)
        {
            MaxTimeout = 1000000
        };

        using RestClient client = new RestClient(options);

        var request = new RestRequest(requestParam.Route, requestParam.Method);
        request.AddHeader("Content-Type", requestParam.ContentType);
        if (requestParam.Parameter != null)
            request.AddBody(requestParam.Parameter);
        var response = await client.ExecuteAsync(request);
        if (response.IsSuccessful)
            return new ApiResponse(true);
        else
        {
            ErrorDto error = JsonConvert.DeserializeObject<ErrorDto>(response.Content);
            return new ApiResponse(error?.error?.message);
        }
    }

    public async Task<ApiResponse<T>> ExecuteAsync<T>(RequestParam requestParam)
    {
        var options = new RestClientOptions(AddressManager.ApiAddress)
        {
            MaxTimeout = 100000
        };

        using RestClient client = new RestClient(options);
        var request = new RestRequest(requestParam.Route, requestParam.Method);
        request.AddHeader("Content-Type", requestParam.ContentType);
        if (requestParam.Parameter != null)
            request.AddBody(requestParam.Parameter);
        var response = await client.ExecuteAsync<T>(request);
        if (response.IsSuccessful)
            return new ApiResponse<T>(true, response.Data);
        else
        {
            try
            {
                ErrorDto error = JsonConvert.DeserializeObject<ErrorDto>(response.Content);
                return new ApiResponse<T>(error?.error?.message);
            }
            catch (Exception ex)
            {
                return new ApiResponse<T>("请求异常");
            }
        }
    }
}